import React,{useState,useEffect,useCallback } from 'react';
import {useNavigate,useLocation} from "react-router-dom";
import { Tabs } from 'antd';
import {connect} from "react-redux";
import {rootRouter} from '@/routers/index'
import {flatArray} from '@/utils/index'

import {setAllRouter} from '@/redux/modules/Menu/action'
import {menuDataType} from '@/redux/interface/index'
import {RouterObj} from '@/routers/interface/index'
import './index.less'

// type TargetKey = React.MouseEvent | React.KeyboardEvent | string;

function TabArea(props:any) {
    const {menuList,setAllRouter} = props
    let { allRouter } = menuList
    const navigate = useNavigate();
    const pathname = useLocation().pathname;
    const [activeKey, setActiveKey] = useState<string>('');
    const [items, setItems] = useState<any[]>([]);
    const { TabPane } = Tabs;
    const addTabs = useCallback(() => {
        if(allRouter !== undefined && allRouter.length>0){
            let currentRouter= allRouter.filter((item:RouterObj)=>{
                return item.path === pathname
            })[0]
            let hasCurrent = items.filter((item)=>item.key === pathname)
            if(JSON.stringify(currentRouter) !== '{}' && hasCurrent.length === 0){
                let list = [...items]
                list.push({label: currentRouter?.meta?.title,  key: currentRouter.path})
                setItems(list)
            }
        }
        setActiveKey(pathname)
    },[allRouter, items, pathname])
    useEffect(()=>{
        if(allRouter=== undefined || allRouter.length === 0){
            let allData:RouterObj[] = flatArray(rootRouter)
            setAllRouter(allData)
        }
        addTabs()
    },[addTabs, allRouter, pathname, setAllRouter])

    const onChange = (path:string) => {
        navigate(path);
    }
    const delTabs = (path:string) => {
        setItems(items.filter(item=>item.key !== path))
    };
    return (
        <div className="tabArea">
            <Tabs
                hideAdd
                onChange={onChange}
                activeKey={activeKey}
                type="editable-card"
                onEdit={path=>delTabs(path as string)}
            >
                {items.map((item,index) => {
                    return (
                        <TabPane key={item.key}
                            tab={
                                <span>{item.label}</span>
                            }
                            closable={index>0}
                        ></TabPane>
                    );
                })}
            </Tabs>
        </div>
    );
}

const mapStateToProps = (state:{menuList:menuDataType})=>{
    return{
        menuList:state.menuList
    }
}
const mapDispatchToProps = { setAllRouter }
export default connect(mapStateToProps,mapDispatchToProps)(TabArea);
